package com.ycb.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ycb.common.Result;
import com.ycb.pojo.Category;
import com.ycb.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 菜品及套餐分类 前端控制器
 * </p>
 *
 * @author ycb
 * @since 2024-09-30
 */
@RestController
@RequestMapping("/category")
@Slf4j
@Transactional(rollbackFor = RuntimeException.class)
public class CategoryController {
    @Autowired
    private ICategoryService categoryService;

    @GetMapping("/page")
    public Result<Page> page(int page,int pageSize) throws Exception{
        Page<Category> categoryPage = new Page<Category>(page,pageSize);
        QueryWrapper<Category> categoryQueryWrapper = new QueryWrapper<>();
        categoryQueryWrapper.orderByAsc("sort");
        categoryService.page(categoryPage,categoryQueryWrapper);
        return Result.success(categoryPage);
    }

    @PostMapping
    public Result<String> save(@RequestBody Category category) throws Exception {
        categoryService.save(category);
        String str = "";
        if (category.getType() == 1) {
            str = "新增套餐分类成功";
        } else {
            str = "新增菜品分类成功";
        }
        return Result.success(str);
    }

    @PutMapping
    public Result<String> update(@RequestBody Category category) throws Exception {
        categoryService.updateById(category);
        // String str = "";
        // if (category.getType() == 1) {
        //     str = "修改套餐分类成功";
        // } else {
        //     str = "修改菜品分类成功";
        // }
        return Result.success("修改分类成功");
    }

    @DeleteMapping
    public Result<String> delete(Long id) throws Exception {
        if (id == null) {
            return Result.error("当前传回的id为空");
        }
        return categoryService.removeIfNotChildren(id);
    }

    @GetMapping("/list")
    public Result<List> list(Integer type) throws Exception {
        List<Category> categories = categoryService.listByType(type);
        return Result.success(categories);
    }
}
